package com.znf4.wechat;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.znf4.cache.redis.RedisUtils;
import com.znf4.utils.BigDecimalUtil;
import com.znf4.utils.DateUtils;
import com.znf4.utils.HttpUtils;
import com.znf4.utils.StringUtil;



/**
 * 微信AccessToken获取工具类
 */
public class AccessTokenUtil {

	private final static Logger log = LoggerFactory.getLogger(AccessTokenUtil.class);
	
	private static final String URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	private static final String TEMPLATEURL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

	public static void main(String[] args) {
		WechatTemplateFundsChangeVo vo = new WechatTemplateFundsChangeVo();
		vo.setAdCharge(new BigDecimal("555"));
		vo.setCashBalance(new BigDecimal("6666.66"));
		vo.setOrderNo("dfd123412341234125679567535");
		vo.setRemark("点击“详情“立即查阅您的帐户记录");
		vo.setMerchantName("阿伟测试商户");
		vo.setUrl("http://pay-gateway.xxxxx.com/wx/auth/toAuth/toQueryTrade/wxdc4e0888857e858d");
		System.out.println(sendTemplateFundsChange(vo, "wxdc4e0888857e858d", "ed873a3e99bb2344c2187f94a425d8ba", "okocOwGt2w6uasvHEakh3SlhjcT4", "58QqQlrYCv_6o0zj9nVpAgHiwE4Hv9S_iEhfdVScaG4"));
	}

	public static String sendTemplateFundsChange(WechatTemplateFundsChangeVo vo, String appid, String appsecret, String openId, String templateId) {
		return sendTemplate(getAccessToken(appid, appsecret), getTemplate2(openId, templateId, vo));
	}

	public static String getAccessToken(String appid, String appsecret) {
		
		long accessToken_til = RedisUtils.getTtl("access_token_" + appid ) ;
		//提前30秒从新获取 微信token
		if(accessToken_til <= 30){
			//每次只能有一个线程去 调用微信的接口，其他线程继续走本地缓存
			if(RedisUtils.getLock()){
				String url = URL.replace("APPID", appid).replace("APPSECRET", appsecret);
				JSONObject json = (JSONObject) JSONObject.parse(HttpUtils.get(url));
				if (StringUtils.isNotBlank(json.getString("access_token"))) {
					RedisUtils.save("access_token_" + appid, json.getString("access_token"), 7000);
					log.info("access_token---------------new-token--------------------"+json.getString("access_token"));
					RedisUtils.releaseLock();
					return json.getString("access_token");
				}
				throw new RuntimeException("调用微信获取AccessToken接口出错：" + url + " 返回：" + json);
			}else{
				Object accessToken = RedisUtils.get("access_token_" + appid);
				log.info("access_token---------------old-token--------------------"+accessToken);
				return accessToken.toString();
			}
		}else{
			Object accessToken = RedisUtils.get("access_token_" + appid);
			log.info("access_token---------------old-token--------------------"+accessToken);
			return accessToken.toString();
		}
		
//		Object accessToken = RedisUtils.get("access_token_" + appid);
//		log.info("access_token---------------old-token--------------------"+accessToken);
//		if (null == accessToken) {
//			String url = URL.replace("APPID", appid).replace("APPSECRET", appsecret);
//			JSONObject json = (JSONObject) JSONObject.parse(HttpUtils.get(url));
//			if (StringUtils.isNotBlank(json.getString("access_token"))) {
//				RedisUtils.save("access_token_" + appid, json.getString("access_token"), 7000);
//				log.info("access_token---------------new-token--------------------"+json.getString("access_token"));
//				return json.getString("access_token");
//			}
//			throw new RuntimeException("调用微信获取AccessToken接口出错：" + url + " 返回：" + json);
//		} else {
//			return accessToken.toString();
//		}
	}

	public static String sendTemplate(String accessToken, String template) {
		String url = TEMPLATEURL.replace("ACCESS_TOKEN", accessToken);
		return HttpUtils.post(url, template);
	}

	/**
	 * 模板1
	 * 
	 * @param openId
	 * @param templateId
	 * @param vo
	 * @return
	 */
	private static String getTemplate1(String openId, String templateId, WechatTemplateFundsChangeVo vo) {
		Map<String, Object> data = new HashMap<>();
		data.put("touser", openId);
		data.put("template_id", templateId);
		data.put("url", vo.getUrl());
		Map<String, Object> map = new HashMap<>();
		map.put("first", getValue("您好，现有一笔资金到账（订单号：{}）".replace("{}", vo.getOrderNo())));
		map.put("date", getValue(DateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss")));
		map.put("adCharge", getValue(BigDecimalUtil.format(vo.getAdCharge(), "#00.00").toString()));
		map.put("type", getValue(""));
		map.put("cashBalance", getValue("请去个人中心查看"));
		map.put("remark", getValue("\r\n" + vo.getRemark()));
		data.put("data", map);
		return JSONObject.toJSONString(data);
	}

	/**
	 * 模板2
	 * 
	 * @param openId
	 * @param templateId
	 * @param vo
	 * @return
	 */
	private static String getTemplate2(String openId, String templateId, WechatTemplateFundsChangeVo vo) {
		Map<String, Object> data = new HashMap<>();
		data.put("touser", openId);
		data.put("template_id", templateId);
		data.put("url", vo.getUrl());

		Map<String, Object> map = new HashMap<>();
		map.put("first", getValue("您好，您的商户交易成功了一笔订单"));
		map.put("keyword1", getValue(DateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss")));
		map.put("keyword2", getValue(vo.getMerchantName()));
		map.put("keyword3", getValue(BigDecimalUtil.format(vo.getAdCharge(), "#0.00").toString()+"\r\n交易单号：" + vo.getOrderNo()));
		map.put("keyword4", getValue("消费"));
//		map.put("keyword4", getValue(BigDecimalUtil.format(vo.getAdCharge(), "#0.00").toString()+"\r\n交易单号：" + vo.getOrderNo()));
		map.put("remark", getValue("\r\n" + vo.getRemark()));
		data.put("data", map);
		return JSONObject.toJSONString(data);
	}

	private static Map<String, Object> getValue(String value) {
		Map<String, Object> v = new HashMap<>();
		v.put("value", value);
		return v;
	}

	// NQxGBBgShXVrQ83gDApLGu0zePPkAHdpR4mfAKBn6lg
	// 7VR-txzoQ68p6yzchIWQvItyYPlyWBXp9TqJTH_yCyVxbP6WHpkX9RNe6QCmSIqeZRkjmDQfjYT7TS3cCIB9KK8xFIxsS286olwNj1rldrX1abcIHyHdXzCMD8tiHe1EHBJaAGAXRZ

}
